package com.cwz.service;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSource;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@Service
@Slf4j
public class DeepSeekService {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private final OkHttpClient okHttpClient = new OkHttpClient();

    public void sendStreamRequest(String userMessage, SseEmitter emitter) throws IOException {

        // 构建请求体
        String json = "{\n" +
                "  \"messages\": [\n" +
                "    {\n" +
                "      \"content\": \"You are a helpful assistant\",\n" +
                "      \"role\": \"system\"\n" +
                "    },\n" +
                "    {\n" +
                "      \"content\": \"" + userMessage + "\",\n" +
                "      \"role\": \"user\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"model\": \"deepseek-chat\",\n" +
                "  \"stream\": true\n" +
                "}";

        RequestBody body = RequestBody.create(JSON, json);

        // 构建请求
        Request request = new Request.Builder()
                .url("https://api.deepseek.com/chat/completions")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer sk-b3b2d13525ca41529356c83c9cf4bdaf") // 替换为你的实际 API Key
                .build();


        log.info("准备发送请求.....");

        log.info("请求URL: {}", request.url());
        log.info("请求头: {}", request.headers());
        log.info("请求体: {}", json);

        // 发送请求并处理流式响应
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                log.error("请求失败，状态码: {}", response.code());
                log.error("错误信息: {}", response.body().string()); // 打印错误响应体
                throw new IOException("Unexpected code: " + response);
            }

            // 读取流式响应
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                log.info("读取响应:{}",responseBody);
                try (BufferedSource source = responseBody.source()) {
                    while (!source.exhausted()) {
                        String line = source.readUtf8Line(); // 读取一行数据
                        if (line != null && !line.isEmpty()) {
                            // 发送到前端
                            emitter.send(SseEmitter.event().data(line));
                        }
                    }
                }
            }
        } finally {
            emitter.complete(); // 完成流式输出
        }
    }
}